<template>
   <div class="app-container" ref="main">

      <el-container>
         <el-header>
            <section class="search_box clearfix">
               <el-row>
                  <el-col :md="12" :lg="8" :xl="6">
                     <label class="search-label">楼盘名称：</label>
                     <el-input v-model="listQuery.houseName" @keyup.enter.native="search" size="mini"
                               class="search-input" placeholder="请输入"
                               clearable @change="search"></el-input>
                  </el-col>
                  <el-col :md="12" :lg="16" :xl="18" class="text_right">
                     <el-button type="primary" icon="el-icon-search" @click="search" size="mini">搜索
                     </el-button>
                     <el-button @click="openDialog('create')" icon="el-icon-edit" type="primary" size="mini">添加
                     </el-button>
                  </el-col>
               </el-row>
            </section>
         </el-header>

         <el-main >
            <!--列表-->
            <el-table :data="list" border fit highlight-current-row
                      :max-height="listHeight">

               <el-table-column align="center" label="序号" prop="index" width="70">
               </el-table-column>

               <el-table-column align="center" label="楼盘id" prop="keyId" min-width="80">
               </el-table-column>

               <el-table-column align="center" label="楼盘名称" prop="houseName" min-width="100">
                  <template slot-scope="scope">
                     <el-button type="text" @click="openDialog('update',scope.row)" size="mini">
                        {{scope.row.houseName}}
                     </el-button>
                  </template>
               </el-table-column>

               <el-table-column align="center" label="咨询电话" prop="houseMobile" min-width="80">
               </el-table-column>

               <el-table-column align="center" label="楼盘户型" width="80">
                  <template slot-scope="scope">
                     <el-button type='primary' size="mini" @click="goHouseType(scope.row)">查看
                     </el-button>
                  </template>
               </el-table-column>

               <el-table-column align="center" label="楼盘动态" width="80">
                  <template slot-scope="scope">
                     <el-button type='primary' size="mini" @click="goDevelopments(scope.row)">查看
                     </el-button>
                  </template>
               </el-table-column>

               <el-table-column align="center" label="操作">
               <template slot-scope="scope">
               <el-button type='danger' size="mini" @click="del(scope.row.keyId)">删除
               </el-button>
               </template>
               </el-table-column>

            </el-table>
         </el-main>

         <el-footer>
            <!--翻页-->
            <div class="pagination-container" v-if="list">
               <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                              :current-page.sync="currentPage"
                              :page-size="listQuery.pageSize" :total="totalElements" :page-sizes="[10, 20, 50, 100]"
                              layout="total, sizes, prev, pager, next, jumper" background>
               </el-pagination>
            </div>
         </el-footer>

      </el-container>

      <!--添加弹出框-->
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="70%"
                 :closeOnClickModal="false">
         <el-form :model="temp" :rules="tempRules" ref="temp" label-width="130px"
                  v-loading="dialogFormVisibleLoading">
            <el-tabs :tab-position="tabPosition" v-model="tabValue">
               <el-tab-pane label="属性1" name="first">
                  <el-row class="form_box">

                     <el-col :span="12">
                        <el-form-item label="楼盘名称" prop="name">
                           <el-input type="text" placeholder="请输入" v-model="temp.houseName"
                                     size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="开盘时间" prop="openTime">
                           <el-date-picker
                              v-model="temp.openTime"
                              type="date" value-format="yyyy-MM-dd"
                              placeholder="选择日期" size="mini">
                           </el-date-picker>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="交房时间" prop="openTime">
                           <el-date-picker
                              v-model="temp.completionTime"
                              type="date" value-format="yyyy-MM-dd"
                              placeholder="选择日期" size="mini">
                           </el-date-picker>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="建筑类别" prop="buildCategory">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.buildCategory" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="装修情况" prop="decorateSituation">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.decorateSituation" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="区域位置" prop="areaPosition">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.areaPosition" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="占地面积" prop="floorSpace">
                           <el-input type="number" placeholder="请输入"
                                     v-model="temp.floorSpace" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="建筑面积" prop="coveredSpace">
                           <el-input type="number" placeholder="请输入"
                                     v-model="temp.coveredSpace" size="mini"></el-input>
                        </el-form-item>
                     </el-col>



                     <el-col :span="12">
                        <el-form-item label="坐标经度" prop="lon">
                           <el-input type="number" placeholder="请输入"
                                     v-model="temp.lon" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="坐标维度" prop="lat">
                           <el-input type="number" placeholder="请输入"
                                     v-model="temp.lat" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="地址" prop="houseAddress">
                           <el-input type="text" placeholder="请输入" v-model="temp.houseAddress"
                                     size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="是否在售" prop="sale">
                           <el-switch v-model="temp.sale"></el-switch>
                        </el-form-item>
                     </el-col>

                     <el-col :span="24">
                        <el-form-item label="概述">
                           <tinymce v-model="temp.summarize" :height="300" v-if="dialogFormVisible"/>
                        </el-form-item>
                     </el-col>

                  </el-row>
               </el-tab-pane>

               <el-tab-pane label="属性2" name="second">
                  <el-row class="form_box">

                     <el-col :span="12">
                        <el-form-item label="产权" prop="propertyRight">
                           <el-input type="number" placeholder="请输入"
                                     v-model="temp.propertyRight" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="容积率" prop="plotRatio">
                           <el-input type="number" placeholder="请输入"
                                     v-model="temp.plotRatio" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="总户数" prop="householdsAmount">
                           <el-input type="number" placeholder="请输入"
                                     v-model="temp.householdsAmount" size="mini"></el-input>
                        </el-form-item>
                     </el-col>
                     <el-col :span="12">
                        <el-form-item label="价格/每平" prop="perFlatPrice">
                           <el-input type="number" placeholder="请输入"
                                     v-model="temp.perFlatPrice" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="开发商" prop="developers">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.developers" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="总价" prop="totalPrice">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.totalPrice" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="咨询电话" prop="houseMobile">
                           <el-input type="number" placeholder="请输入"
                                     v-model="temp.houseMobile" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="物业公司" prop="propertyCompany">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.propertyCompany" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="物业费" prop="propertyFee">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.propertyFee" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="车位配比" prop="parkingSpace">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.parkingSpace" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="价格标签" prop="priceLabel">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.priceLabel" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="位置标签" prop="positionLabel">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.positionLabel" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="地区标签" prop="areaLabel">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.areaLabel" size="mini"></el-input>
                        </el-form-item>
                     </el-col>

                     <el-col :span="12">
                        <el-form-item label="其他标签" prop="otherLabel">
                           <el-input type="text" placeholder="请输入"
                                     v-model="temp.otherLabel" size="mini"></el-input>
                        </el-form-item>
                     </el-col>
                  </el-row>
               </el-tab-pane>

               <el-tab-pane label="照片" name="third">
                  <section class="picture_wrap">
                     <label>照片</label>
                     <el-upload action="https://upload.qiniup.com" list-type="picture-card"
                                :on-success="handleSuccess_big" :before-upload="beforeUpload"
                                :on-remove="handleRemove_big" :data="uploadData"
                                class="avatar-uploader" accept="image/*"  :file-list="housePicture">
                        <i class="el-icon-plus"></i>
                     </el-upload>
                     <el-dialog size="tiny">
                        <img v-if="housePicture" :src="housePicture" width="100%" class="avatar">
                     </el-dialog>
                  </section>
               </el-tab-pane>


            </el-tabs>
         </el-form>

         <div slot="footer">
            <el-button v-if="dialogStatus==='create'" type="primary" @click="create(temp)"
                       size="mini" :loading="tempLoading">提 交
            </el-button>
            <el-button v-else type="primary" @click="update(temp)" size="mini" :loading="tempLoading">提 交
            </el-button>
         </div>
      </el-dialog>

   </div>
</template>

<script>
   import buildingApi from "api/building";
   import sassApi from "api/saasService";
   import common from "utils/common";
   import Tinymce from "@/components/Tinymce";

   export default {
      components: {Tinymce},
      data() {
         return {
            tabPosition: "left",  //tab导航位置
            tabValue: "first",
            listHeight: 0,  //动态列表高度
            totalElements: 0,   //总条数
            currentPage: 1,     //当前页

            list: null,       //列表
            tempLoading: false, //提交加载动画

            //搜索
            listQuery: {
               page: 1,
               pageSize: 10,
               houseName: null,
               cityId: sessionStorage.getItem('ledaoCityId')
            },


            //添加/修改
            dialogFormVisible: false,
            textMap: {
               update: "编辑",
               create: "创建"
            },
            dialogStatus: null, //添加/修改状态
            dialogFormVisibleLoading: false, //弹出框加载动画
            temp: {
               housePicture: "",
               houseName: "",
               houseMobile: "",
               houseAddress: "",
               perFlatPrice: "",
               summarize: "",
               openTime: "",
               completionTime: "",
               buildCategory: "",
               decorateSituation: "",
               areaPosition: "",
               floorSpace: "",
               coveredSpace: "",
               propertyRight: "",
               plotRatio: "",
               householdsAmount: "",
               developers: "",
               propertyCompany: "",
               propertyFee: "",
               parkingSpace: "",
               priceLabel: "",
               positionLabel: "",
               areaLabel: "",
               otherLabel: "",
               lon: "",
               lat: "",
               totalPrice: "",
               sale : true,
               cityId: sessionStorage.getItem('ledaoCityId')
            },
            tempRules: {
               // 验证规则
               // name: [{required: true, message: "请填写互助计划名称", trigger: "blur"}],
            },

            housePicture: [],
            uploadData: {
               key: "",
               token: ""
            },

         };
      },

      methods: {
         del(keyId) {
            this.$confirm("您确定删除当前数据吗？", "提示", {
               confirmButtonText: "确定",
               cancelButtonText: "取消",
               type: "warning"
            }).then(() => {
               buildingApi.delete(keyId).then(res => {
                  if (res.code === 1) {
                     this.$notify({
                        title: "成功",
                        message: "删除成功",
                        type: "success",
                        customClass: "success",
                        duration: 1500
                     });
                     this.getList();
                  } else {
                     this.$notify.error({
                        title: "错误",
                        message: res.msg,
                        customClass: "error",
                        duration: 1500
                     });
                  }
               });
            });
         },

         goDevelopments(row) {
            this.$router.push({
               path: "developments",
               query: {
                  keyId: row.keyId,
                  listQuery: JSON.stringify(this.listQuery),
               }
            });
         },

         goHouseType(row) {
            this.$router.push({
               path: "houseType",
               query: {
                  keyId: row.keyId,
                  listQuery: JSON.stringify(this.listQuery),
               }
            });
         },

         //提交数据清空
         resetTemp() {
            this.tabValue = "first";
            this.temp.houseName = "";
            this.temp.sale  = true;
            this.temp.houseMobile = "";
            this.temp.houseAddress = "";
            this.temp.perFlatPrice = "";
            this.temp.summarize = "";
            this.temp.openTime = "";
            this.temp.completionTime = "";
            this.temp.buildCategory = "";
            this.temp.decorateSituation = "";
            this.temp.areaPosition = "";
            this.temp.floorSpace = "";
            this.temp.coveredSpace = "";
            this.temp.propertyRight = "";
            this.temp.plotRatio = "";
            this.temp.householdsAmount = "";
            this.temp.developers = "";
            this.temp.propertyCompany = "";
            this.temp.propertyFee = "";
            this.temp.parkingSpace = "";
            this.temp.priceLabel = "";
            this.temp.positionLabel = "";
            this.temp.areaLabel = "";
            this.temp.otherLabel = "";
            this.temp.lon = "";
            this.temp.lat = "";
            this.temp.totalPrice = "";

            this.$nextTick(() => {
               this.$refs["temp"].clearValidate();   //对表单验证进行重置。
            });
         },

         //打开弹窗
         openDialog(dialogStatus, row) {
            this.dialogStatus = dialogStatus;
            this.dialogFormVisible = true;
            this.housePicture = [];
            this.temp.housePicture = "";
            this.resetTemp();
            if (dialogStatus === "update") {
               this.temp = Object.assign({}, row);
               if (this.temp.housePicture) {
                  const arr = this.temp.housePicture.split(",");
                  for (let i = 0; i < arr.length; i++) {
                     this.housePicture.push({name: "i.jpg", url: arr[i]});
                  }
               }
            }
         },

         //处理图片
         handlePicture() {
            this.temp.housePicture = [];
            for (let i = 0; i < this.housePicture.length; i++) {
               this.temp.housePicture.push(this.housePicture[i].url);
            }
            this.temp.housePicture = this.temp.housePicture.join(",");
         },


         //添加
         create() {
            if (this.housePicture.length === 0) {
               this.$notify.warning({
                  title: "提示",
                  message: "请上传图片",
                  customClass: "warning",
                  duration: 1500,
               });
               return;
            }
            this.handlePicture();
            this.$refs.temp.validate(valid => {
               if (valid) {
                  this.tempLoading = true;
                  if (this.temp.summarize) {
                     const reg = new RegExp( '<p>&nbsp;</p>' , "g" );
                     this.temp.summarize = this.temp.summarize.replace(reg,'<p style="height: 30px">&nbsp;</p>');

                     const reg1 = new RegExp( '<strong>' , "g" );
                     this.temp.summarize = this.temp.summarize.replace(reg1,'<strong style="font-weight: 700">');

                     const reg2 = new RegExp( '&nbsp;' , "g" );
                     this.temp.summarize = this.temp.summarize.replace(reg2,'<span style="display: inline-block;color: transparent;opacity: 0">a</span>');
                  }
                  buildingApi.add(this.temp).then(res => {
                     let self = this;
                     setTimeout(function () {
                        self.tempLoading = false;
                     }, 2000);
                     if (res.code === 1) {
                        this.$notify({
                           title: "成功",
                           message: "添加成功",
                           type: "success",
                           customClass: "success",
                           duration: 1500
                        });
                        this.getList();
                        this.resetTemp();
                        this.dialogFormVisible = false;
                     } else {
                        this.$notify.error({
                           title: "失败",
                           message: res.msg,
                           customClass: "error",
                           duration: 1500
                        });
                     }
                  });
               } else {
                  this.$notify.warning({
                     title: "信息不完整",
                     message: "请完整填写信息",
                     customClass: "warning",
                     duration: 1500
                  });
               }
            });
         },

         //修改
         update() {
            if (!this.housePicture) {
               this.$notify.warning({
                  title: "提示",
                  message: "请上传图片",
                  customClass: "warning",
                  duration: 1500,
               });
               return;
            }
            this.handlePicture();
            this.$refs.temp.validate(valid => {
               if (valid) {
                  this.tempLoading = true;
                  if (this.temp.summarize) {
                     const reg = new RegExp( '<p>&nbsp;</p>' , "g" );
                     this.temp.summarize = this.temp.summarize.replace(reg,'<p style="height: 30px">&nbsp;</p>');

                     const reg1 = new RegExp( '<strong>' , "g" );
                     this.temp.summarize = this.temp.summarize.replace(reg1,'<strong style="font-weight: 700">');

                     const reg2 = new RegExp( '&nbsp;' , "g" );
                     this.temp.summarize = this.temp.summarize.replace(reg2,'<span style="display: inline-block;color: transparent;opacity: 0">a</span>');
                  }
                  buildingApi.update(this.temp).then(res => {
                     let self = this;
                     setTimeout(function () {
                        self.tempLoading = false;
                     }, 2000);
                     if (res.code === 1) {
                        this.$notify({
                           title: "成功",
                           message: "修改成功",
                           type: "success",
                           customClass: "success",
                           duration: 1500
                        });
                        this.getList();
                        this.resetTemp();
                        this.dialogFormVisible = false;

                     } else {
                        this.$notify.error({
                           title: "失败",
                           message: res.msg,
                           customClass: "error",
                           duration: 1500
                        });
                     }
                  });
               } else {
                  this.$notify.warning({
                     title: "信息不完整",
                     message: "请完整填写信息",
                     customClass: "warning",
                     duration: 1500,
                  });
               }
            });
         },

         //列表
         getList() {
            buildingApi.pageList(this.listQuery).then(res => {
               this.list = res.data.content.map((d, i) => {
                  d.index = (this.currentPage - 1) * this.listQuery.pageSize + i + 1;
                  return d;
               });
               this.totalElements = res.data.totalElements;
            });
         },

         //大图片上传
         handleSuccess_big(res, file) {
            this.housePicture.push({name: res.key, url: "https://testqn.weilong1993.com/" + res.key});
         },
         handleRemove_big(file, fileList) {
            this.housePicture = fileList;
         },
         beforeUpload(file) {
            let self = this;
            let parts = file.name.split(".");//split() 方法用于把一个字符串分割成字符串数组。
            let fileType = parts[parts.length - 1];
            return sassApi.getUploadToken().then(function (res) {
               self.uploadData.token = res.data;
               self.uploadData.key = common.getNowStr() + "." + fileType;
            });
         },

         search() {
            this.listQuery.page = this.currentPage = 1;
            this.getList();
         },

         //控制列表显示条数
         handleSizeChange(val) {
            this.listQuery.page = 1;
            this.listQuery.pageSize = val;
            this.getList();
         },

         handleCurrentChange() {
            this.listQuery.page = this.currentPage;
            this.getList();
         },
      },

      mounted() {
         this.$nextTick(() => {
            this.listHeight = this.$refs.main.offsetHeight - 175;
            let self = this;
            window.addEventListener("resize", function () {
               self.listHeight = self.$refs.main.offsetHeight - 175;
            });
         });
      },

      created() {
         if (this.$route.query.listQuery) {
            Object.assign(this.listQuery, JSON.parse(this.$route.query.listQuery));
            this.currentPage = this.listQuery.page;
         }

         this.getList();
      },
   }
   ;
</script>